package com.zhr.tea.view.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.widget.ImageView;

import com.alibaba.fastjson.JSONObject;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhr.tea.R;
import com.zhr.tea.entity.shouye.Wangqi;
import com.zhr.tea.view.adapter.ShouyeJingcaiAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class ShouyeJingcaiActivity extends AppCompatActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.xlv)
    XRecyclerView xlv;
    private List<Wangqi.ContentBean> data = new ArrayList<>();
    private ShouyeJingcaiAdapter adapter;
    private int beginId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shouye_jingcai);
        ButterKnife.bind(this);
        initView();
        initData();
        refresh();
    }

    private void refresh() {
        xlv.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                   beginId=0;
                    initData();
            }

            @Override
            public void onLoadMore() {
            beginId+=10;
                initData();
            }
        });
    }

    private void initData() {
        RequestParams params = new RequestParams();
        params.addHeader("Content-Type", "application/json");
        JSONObject obj = new JSONObject();
        obj.put("beginId", beginId + "");
        obj.put("count", "20");
        params.applicationJson(obj);
        HttpRequest.post("http://120.55.137.143:54321/service/teabubble/ad?methods=searchThemePage", params, new BaseHttpRequestCallback<Wangqi>() {
            @Override
            protected void onSuccess(Wangqi wangqi) {
                super.onSuccess(wangqi);
                data.addAll(wangqi.getContent());
                adapter.notifyDataSetChanged();
                xlv.refreshComplete();
                xlv.loadMoreComplete();
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    private void initView() {
        adapter = new ShouyeJingcaiAdapter(this, data);
        xlv.setLayoutManager(new LinearLayoutManager(this));
        xlv.setAdapter(adapter);
    }

    @OnClick(R.id.iv_back)
    public void onClick() {
        finish();
    }
}
